import {defineStore} from "pinia"
import mockRequest from "@/mock/request"
import initUserListTable from "./initUserTable"
import {authBtnMode} from "@/common/config"

export const actionKeys={
  queryList:authBtnMode=='request'?'userListQuery':'query',
  add:authBtnMode=='request'?'userAdd':'add',
  update:authBtnMode=='request'?'userUpdate':'update',
  delete:authBtnMode=='request'?'userDelete':'delete',
}

export default defineStore('userList',{
    state:()=>({
      list:[] as userType[]
    }),
    actions:{
       /** 
      @requestName userListQuery  接口权限值
     **/
       async getList(){
        const res = await mockRequest(()=>({
          code: 200,
          list: this.list.length ? this.list : initUserListTable,
        }))
        if (res && res.code) {
          this.list = res.list
          return { code: 200, list: res.list }
        }
        return { code: 0 }
       },
     /** 
      @requestName userDelete  接口权限值
     **/
       async deleteItem(id:string | number){
        const res=await mockRequest(()=>{
         this.list.splice(this.list.findIndex(v=>v.id==id),1)
         return ({code:200}) 
        },false)
        if(res&&res.code) return{code:200}
        return{code:0}
     },
     /** 
      @requestName userAdd  接口权限值
     **/
     async addItem(user:userType){
        const res=await mockRequest(()=>{
         if(!this.list.find(v=>user.userName==v.userName))
             {
               this.list.unshift(user)
               return ({code:200})
             }
             else  return ({code:201})
        })
        if (res && res.code == 200) {return { code: 200 }}
        if (res && res.code == 201) return { code: 201,msg:'已存在'}
        return { code: 0 }
     },
     /** 
      @requestName userUpdate  接口权限值
     **/
     async updateItem(user:userType){
        const res=await mockRequest(()=>{
         if(!this.list.find(v=>v.id!=user.id && user.userName==v.userName))
         {
           const item=this.list.find(v=>v.id==user.id)
           Object.keys(user).forEach((k)=>{
           item![k]=user[k]
         })
           return({code:200})
         }
         else return({code:201})
        })
        if (res && res.code == 200) {return { code: 200 }}
        if (res && res.code == 201) return { code: 201,msg:'已存在'}
        return { code: 0 }
     },
    },
    

})